<?php
/**
 * Created by PhpStorm.
 * User: WYJ
 * Date: 2018/6/13
 * Time: 14:17
 */

namespace zhtfrontend\components\services\customermanage;

use yii\base\Component;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\CustomerRelationship;
use yii\data\Pagination;
use yii\db\Query;

class Index extends Component
{

    public static function show($param)
    {
        $site_id = Fun::getSiteId();
        $model = [];
        $data = CustomerRelationship::find()->where(['site_id' => $site_id,'id'=>1]);
        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);
            //手机号搜索
            if (!empty($search_data['tel'])) {
                $data->andWhere(['mobile' => $search_data['tel']]);
            }
            //姓名搜索
            if (!empty($search_data['name'])) {
                $data->andWhere(['name' => $search_data['name']]);
            }
            //意向分类搜索
            if (!empty($search_data['category_id'])) {
                $data->andWhere(['category_id' => $search_data['category_id']]);
            }
            //获客渠道搜索
            if (!empty($search_data['source'])) {
                $data->andWhere(['source' => $search_data['source']]);
            }
            //客户类型搜索
            if (!empty($search_data['status'])) {
                $data->andWhere(['status' => $search_data['status']]);
            }
        }
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'customer_manager') {
            $data->andWhere(['admin_id' => \Yii::$app->user->identity->id]);;
        }
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 20;
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;

        if (isset(\Yii::$app->user->identity) && in_array(\Yii::$app->user->identity->role, ['admin', 'administrator'])) {
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        } else {
            if (!empty($param['searchData']['tel']) || !empty($param['searchData']['name'])) $model = $data->all();
        }

        //匹配手机号，如果customer表中有数据则以customer表为准
        foreach ($model as $k => $v) {
            $customer = (new Query())->select('*')->from('{{%customer}}')->where(['mobile' => $v->mobile])->one();
            if (isset($customer) && !empty($customer)) {
                $v->name = $customer['name'];
                $v->sex = ($customer['sex'] == 'Female') ? '1' : '0';
            }
            $data_array[] = $v;
        }

        $array = Fun::asArray($data_array, ['operate']);

        return ['data' => $array, 'page' => $pages];
    }
}